import React, {useEffect, useRef, useState} from "react";
import {PageContainer} from "@ant-design/pro-layout";
import ProForm, {
  ProFormDateTimePicker,
  ProFormInstance,
  ProFormMoney,
  ProFormText,
} from "@ant-design/pro-form";
import {Button, Col, message, Row} from "antd";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc"
dayjs.extend(utc)
import {queryFamily, queryPayment} from "@/pages/User/Account/settings/components/service";
import ProCard from "@ant-design/pro-card";
import PaymentLogs from "@/pages/PaymentLogs";
import {addPayment} from "@/pages/Payment/service";
import {Selector} from "antd-mobile";

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: any) => {
  const hide = message.loading('正在处理...');

  try {
    const res = await addPayment({...fields});
    if(res && res.status === "done"){
      hide();
      message.success(res.message);
      return true;
    }else {
      hide()
      message.error(res.message);
      return false;
    }
  } catch (error) {
    hide();
    message.error('记录失败请重试！');
    return false;
  }
};
const IncomeForm: React.FC = ()=>{
  const formRef = useRef<ProFormInstance>();
  const [defaultType, setDefaultType] = useState<string[]>([])
  const [defaultUseBy, setDefaultUseBy] = useState<string[]>([])
  const [logUpdate, setLogUpdate] = useState<boolean>(false)

  useEffect(()=>{
    formRef.current?.setFieldsValue({
      payTypeId: defaultType[0],
    })
  }, [defaultType])

  useEffect(()=>{
    formRef.current?.setFieldsValue({
      familyTypeId: defaultUseBy[0],
    })
  }, [defaultUseBy])

  // const formItemLayout ={
  //   labelCol: { span: 6 },
  //   wrapperCol: { span: 18 },
  // }

  // 支出分类options
  const [typeDataSource, setTypeDatasource] = useState<any[]>([])

  // 从后台获取支出分类数据
  useEffect(() => {
    queryPayment().then((res)=>{
      if (res.status === "done"){
        // 数据获取成功
        // 整理list为prolist对象
        let data = [...typeDataSource];

        // 先清空
        data.splice(0, data.length)

        // 填充新数据
        // eslint-disable-next-line array-callback-return
        res.data?.map((item: any)=>{
          data.push({
            label: item.name,
            value: item.id,
          })
        })
        setDefaultType([data[0]?.value])
        setTypeDatasource(data)
      }
    })
  }, []);

  const [useBydataSource, setUseByDatasource] = useState<any[]>([])

  // 从后台获取用户对象数据
  useEffect(() => {
    queryFamily().then((res)=>{
      if (res.status === "done"){
        // 数据获取成功
        // 整理list为prolist对象
        let data = [...useBydataSource];

        // 先清空
        data.splice(0, data.length)

        // 填充新数据
        // eslint-disable-next-line array-callback-return
        res.data?.map((item: any)=>{
          data.push({
            label: item.name,
            value: item.id,
          })
        })
        setDefaultUseBy([data[0]?.value])
        setUseByDatasource(data)
      }
    })
  }, []);

  return(
    <PageContainer pageHeaderRender={false} breadcrumbRender={false}>
      <ProCard
        style={{
          marginBlockStart: 8,
        }}
        gutter={2}
        ghost
      >
        <ProCard
          colSpan={{
            xs: '310px',
            sm: '310px',
            md: '310px',
            lg: '310px',
            xl: '310px',
          }}
          bordered
          style={{height: `calc(100vh - 100px)`}}
        >
          <ProForm
            formRef={formRef}
            onFinish={async (value) => {
              const success = await handleAdd(value);
              if (success) {
                formRef.current?.setFieldsValue({
                  money: null,
                  remark: null,
                  time: dayjs(new Date()).utc().format(),
                  payTypeId: defaultType[0],
                  familyTypeId: defaultUseBy[0],
                })

                // 更新标志，更新流水
                if (logUpdate) {
                  setLogUpdate(false)
                }else {
                  setLogUpdate(true)
                }
              }
            }}
            submitter={{
              render:false
            }}
          >
            <ProFormText
              name={"payTypeId"}
              hidden
            />
            <ProFormText
              name={"familyTypeId"}
              hidden
            />
            <ProFormMoney
              name={"money"}
              label={"金额"}
              placeholder={"0.00"}
              rules={[{required:true, message:'金额必填！'}]}
            />
            <ProFormDateTimePicker
              name={"time"}
              label={"时间"}
              initialValue={`${dayjs(new Date()).utc().format()}`}
              fieldProps={{
                style: {"width": "100%"},
                onChange : (value) => {
                  formRef.current?.setFieldsValue({
                    time: dayjs(value).utc().format()
                  })
                }
              }}
            />
            <Row style={{marginBottom: 10}}>
              <span style={{marginBottom: 8}}>支出分类</span>
              <Col span={24}>
                <Selector
                  key={Date.now()}
                  columns={4}
                  options={typeDataSource}
                  defaultValue={defaultType}
                  multiple={false}
                  showCheckMark={false}
                  style={{
                    '--checked-color': "#fa541c",
                    '--checked-text-color': "white",
                    '--gap': "3px",
                  }}
                  onChange={(value)=>{
                    formRef.current?.setFieldsValue({
                      payTypeId: value[0]
                    })
                  }}
                />
              </Col>
            </Row>
            <Row style={{marginBottom: 10}}>
              <span style={{marginBottom: 8}}>支出对象</span>
              <Col span={24}>
                <Selector
                  key={Date.now()}
                  columns={4}
                  options={useBydataSource}
                  defaultValue={defaultUseBy}
                  multiple={false}
                  showCheckMark={false}
                  style={{
                    '--checked-color': "#fa541c",
                    '--checked-text-color': "white",
                    '--gap': "3px",
                  }}
                  onChange={(value)=>{
                    formRef.current?.setFieldsValue({
                      familyTypeId: value[0]
                    })
                  }}
                />
              </Col>
            </Row>

            {/*<ProFormRadio.Group*/}
            {/*  name={"useBy"}*/}
            {/*  label={"对象"}*/}
            {/*  radioType="button"*/}
            {/*  fieldProps={{*/}
            {/*    buttonStyle: "solid",*/}
            {/*  }}*/}
            {/*  request={async () => {*/}
            {/*    const res = await queryFamily();*/}
            {/*    const options: RequestOptionsType[] | PromiseLike<RequestOptionsType[]> | { label: any; value: any; }[] = [];*/}
            {/*    if (res.status === "done"){*/}
            {/*      if (res.data) {*/}
            {/*        setDefaultUseBy(res.data[0])*/}
            {/*      }*/}
            {/*      // eslint-disable-next-line array-callback-return*/}
            {/*      res.data.map((item: string) => {*/}
            {/*        options.push({ "label": item, "value": item})*/}
            {/*      })*/}
            {/*    }*/}
            {/*    return options*/}
            {/*  }}*/}
            {/*/>*/}
            <ProFormText
              name={"remark"}
              label={"备注"}
              placeholder={"请输入备注"}
            />
            <Row>
              <Button type={"primary"} onClick={()=>{formRef.current?.submit()}}>记一笔</Button>
            </Row>
          </ProForm>
        </ProCard>
        <ProCard bordered style={{height: `calc(100vh - 100px)`, backgroundColor: "white", overflowY:"hidden"}} ghost>
          <PaymentLogs update={logUpdate}/>
        </ProCard>
      </ProCard>
    </PageContainer>
  )
}

export default IncomeForm;
